cloud = require('wx-server-sdk')
cloud.init()

// 主函数入口
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  const db = cloud.database()
  const checkInCol = db.collection('checkInRecords')
  
  // 使用UTC时间
  const today = new Date()
  const dateStr = `${today.getUTCFullYear()}/${today.getUTCMonth()+1}/${today.getUTCDate()}`
  const timeStr = `${today.getHours()+8}:${today.getMinutes()-1}:${today.getSeconds()}`
  
  // 查询今日是否已打卡
  const { data } = await checkInCol.where({
    openid: wxContext.OPENID,
    date: dateStr
  }).get()
  
  if (data.length > 0) {
    return { success: false, msg: '今日已打卡' }
  }
  
  // 记录打卡信息到数据库
  await checkInCol.add({
    data: {
      openid: wxContext.OPENID,
      date: dateStr,
      time: timeStr,
      createTime: db.serverDate() // 使用服务器时间
    }
  })
  
  return { 
    success: true,
    time: timeStr
  }
}